package com.eleventwelve.iris.web.controller;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.opentides.bean.FileInfo;
import org.opentides.service.FileInfoService;
import org.opentides.util.StringUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.eleventwelve.iris.utilities.ImageUtil;

public class ScannedFileImageController extends AbstractController{
	private static final Logger _log = Logger
			.getLogger(UserImageController.class);
	private FileInfoService fileInfoService;
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Long id = StringUtil.convertToLong(request.getParameter("id"),
				-1);

		@SuppressWarnings("deprecation")
		String defaultImage = request.getRealPath("")
				+ "/images/iris/iris-male.jpg";
		
		byte[] barray = null;
		
		OutputStream outputStream = response.getOutputStream();

		try {
			
			FileInfo fileInfo = fileInfoService.load(id);
			String filePath = fileInfo.getFullPath();
			
			barray = ImageUtil.loadImage(filePath);
			
			if(barray == null){
				barray = ImageUtil.loadImage(defaultImage);
			}
			
			if (barray != null) {
				response.setContentType("image/jpeg");
				response.setHeader("Cache-Control", "public");
				outputStream.write(barray);
			}
			
		} catch (Exception e) {
			_log.error("Failed to load image.", e);
		} finally {
			outputStream.flush();
			outputStream.close();
		}
		return null;
	}
	
	public FileInfoService getFileInfoService() {
		return fileInfoService;
	}


	public void setFileInfoService(FileInfoService fileInfoService) {
		this.fileInfoService = fileInfoService;
	}

}
